package com.njmaomao.gj.pyot.domain.wechat;

import com.njmaomao.gj.pyot.common.ResponseCode;
import com.njmaomao.gj.pyot.common.exception.SystemBizFail;
import com.njmaomao.gj.pyot.domain.wechat.wechatapi.WechatApiService;
import com.njmaomao.gj.pyot.domain.wechat.wechatapi.sandboxnew.GetSignkeyReq;
import com.njmaomao.gj.pyot.domain.wechat.wechatapi.sandboxnew.GetSignkeyResp;
import lombok.Getter;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Optional;

@Component
@Getter
@Setter
@ConfigurationProperties(prefix = "wechatpay")
public class PayConfigFactory {

    // Map<appId, PayConfig>
    private Map<String, PayConfig> appgroup;

    @Value("${wechatpay.notifyUrl.pay}")
    private String payNotifyUrl;

    @Value("${wechatpay.notifyUrl.refund}")
    private String refundNotifyUrl;

    @Autowired
    private WechatApiService wechatApiService;

    public PayConfig get(String appId, Optional<String> mchIdOpt, boolean isSandbox) {

        PayConfig payConfig;
        if(isSandbox) {
            payConfig = getPayConfig(appId, mchIdOpt);
            GetSignkeyResp getSignkeyResp = wechatApiService.getsandboxsignkey(GetSignkeyReq.build(payConfig.getMchId(), payConfig));
            payConfig.setKey(getSignkeyResp.getSandboxSignkey());
        } else {
            payConfig = getPayConfig(appId, mchIdOpt);
        }
        return payConfig;

    }

    public PayConfig get(String appId, String mchId) {
        return get(appId, Optional.ofNullable(mchId), false);
    }

    private PayConfig getPayConfig(String appId, Optional<String> mchIdOpt) {
        PayConfig payConfig = appgroup.get(appId);
        SystemBizFail.whenIf(null == payConfig, ResponseCode.PAYTO.UNKNOW_APPID);
        if(mchIdOpt.isPresent() && !payConfig.getMchId().equals(mchIdOpt)) {
            SystemBizFail.whenIf(null == payConfig, ResponseCode.PAYTO.UNKNOW_MCHID);
        }
        PayConfig newPayConfig = payConfig.copy();
        newPayConfig.setAppid(appId);
        return newPayConfig;
    }

}
